package com.dadao.mybatis.binding;

import org.apache.ibatis.session.SqlSession;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 创建MapperProxy代理对象的工厂类
 */
public class ZMapperProxyFactory<T> {
    private final Class<T> mapperInterface;
    private final Map<Method, ZMapperProxy> methodCache = new ConcurrentHashMap<Method, ZMapperProxy>();

    public ZMapperProxyFactory(Class<T> mapperInterface) {
        this.mapperInterface = mapperInterface;
    }

    public Class<T> getMapperInterface() {
        return mapperInterface;
    }

    public Map<Method, ZMapperProxy> getMethodCache() {
        return methodCache;
    }

    protected T newInstance(org.apache.ibatis.binding.MapperProxy<T> mapperProxy) {
        return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[]{mapperInterface}, mapperProxy);
    }

    public T newInstance(SqlSession sqlSession) {
        final org.apache.ibatis.binding.MapperProxy<T> mapperProxy = new ZMapperProxy<T>(sqlSession, mapperInterface, methodCache);
        return newInstance(mapperProxy);
    }
}
